package com.travel.dao.impl;

import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.List;
import java.util.Objects;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.travel.core.AbstractDao;
import com.travel.dao.IUserDao;
import com.travel.struts.form.PreferForm;
import com.travel.struts.form.UserForm;

/**
 * @author SAGITTAR
 */
public class UserDaoImpl extends AbstractDao implements IUserDao {

    private static final Logger LOGGER = LogManager.getLogger(UserDaoImpl.class);

    @Override
    public int checkManager(UserForm userForm) {
        int flag = -1;
        String sqlExist = "SELECT * FROM user WHERE name = ?";
        List<UserForm> userFormList = selectListByClassTypeAndSql(UserForm.class, sqlExist, userForm.getName());
        if (Objects.nonNull(userFormList) && userFormList.size() > 0) {
            // 有该用户
            UserForm firstUserForm = userFormList.get(0);
            if (StringUtils.equals(firstUserForm.getPassword(), userForm.getPassword())) {
                if (StringUtils.equals(firstUserForm.getRank(), "0")) {
                    flag = 1;
                    if (userFormList.size() > 1) {
                        flag = 0;
                    }
                }
                if (StringUtils.equals(firstUserForm.getRank(), "1")) {
                    flag = 3;
                }
            }
        } else {
            flag = 0;
        }
        return flag;
    }

    @Override
    public int register(UserForm userForm) {
        int flag = -1;
        String sqlExist = "SELECT * FROM user WHERE name = ?";
        List<UserForm> userFormList = selectListByClassTypeAndSql(UserForm.class, sqlExist, userForm.getName());
        if (Objects.nonNull(userFormList) && userFormList.size() > 0) {
            flag = 2;
        }
        String sex = userForm.getSex();
        try {
            sex = Objects.isNull(sex) ? StringUtils.EMPTY : new String(sex.getBytes("ISO8859_1"), "gbk").trim();
        } catch (UnsupportedEncodingException e) {
            LOGGER.error(e.getLocalizedMessage(), e);
            return 0;
        }
        String sqlInsert = "INSERT INTO user(name, password, rank, sex, age, address) VALUES(?, ?, '0', ?, ?, ?)";
        Object[] params = new Object[] { userForm.getName(), userForm.getPassword(), userForm.getSex(),
                userForm.getAge(), userForm.getAddress() };
        UserForm insertedEntity = insert(UserForm.class, sqlInsert, params);
        PreferForm preferForm = insertPrefer(insertedEntity.getId());
        if (Objects.nonNull(insertedEntity) && Objects.nonNull(preferForm)) {
            flag = 1;
        }
        return flag;
    }

    @Override
    public int updatePassword(UserForm userForm) {
        // 为何不是ID匹配
        return update("UPDATE user SET password = ? where name = ?", userForm.getPassword(), userForm.getName());
    }

    /**
     * 插入偏好设置，初始化值添加用户ID，其余默认为“0”
     *
     * @param userId
     * @return
     */
    private PreferForm insertPrefer(int userId) {
        // 其余默认为“0”
        String sql = "INSERT INTO prefer(user_id) VALUES(?)";
        PreferForm preferForm = null;
        try {
            preferForm = new QueryRunner(getMysqlDataSource()).insert(sql, new BeanHandler<>(PreferForm.class), userId);
        } catch (SQLException e) {
            printErrorLog(e);
        }
        return preferForm;
    }
}
